﻿Imports Negocio
Imports Utilitario
Public Class frmDescuentos

    Dim servicio1 As New PedidoNegocio
    Dim servicio2 As New ArticuloNegocio
    Dim util As New Utiles

    Dim CIA As String = "01"
    Dim SUC As String = "01"

    Sub cargarSubFamiliasXLineaXFamilia(codLinea As String, codFamilia As String, combo As ComboBox)
        Dim ds As DataSet = servicio1.listarSubFamiliasXLineaXFamilia(codLinea, codFamilia)
        With combo
            .DataSource = ds.Tables(0)
            .ValueMember = "SFM_Codigo"
            .DisplayMember = "SFM_Descripcion"
        End With
    End Sub

    Sub cargarFamiliasXLinea(codLinea As String, combo As ComboBox)
        Dim ds As DataSet = servicio1.listarFamiliasXLinea(codLinea)
        With combo
            .DataSource = ds.Tables(0)
            .ValueMember = "FAM_Codigo"
            .DisplayMember = "FAM_Descripcion"
        End With
    End Sub

    Sub cargarLineas(combo As ComboBox)
        Dim ds As DataSet = servicio1.listarLineas()
        With combo
            .DataSource = ds.Tables(0)
            .ValueMember = "LIN_Codigo"
            .DisplayMember = "LIN_Descripcion"
        End With
    End Sub

    Sub iniciar()
        cargarLineas(cboLineas)
    End Sub

    Private Sub frmDescuentos_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        iniciar()
    End Sub

    Private Sub cboLineas_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles cboLineas.SelectedValueChanged
        cargarFamiliasXLinea(cboLineas.SelectedValue.ToString, cboFamilias)
    End Sub

    Private Sub cboFamilias_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles cboFamilias.SelectedValueChanged
        cargarSubFamiliasXLineaXFamilia(cboLineas.SelectedValue.ToString, cboFamilias.SelectedValue.ToString, cboSubFamilias)
    End Sub

    Private Sub txtProveedor_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtProveedor.KeyDown
        Dim texto As String = txtProveedor.Text.Trim
        If e.KeyValue = Keys.Add Then
            Dim ds As DataSet = servicio1.listarProveedores("")
            Dim frmprov As New frmProveedor(ds, 2)
            If frmprov.ShowDialog() = Windows.Forms.DialogResult.OK Then

            End If
        ElseIf e.KeyValue = Keys.Enter Then
            If texto = "" Then
                lblProveedor.Text = ""
            Else
                Dim ds As DataSet = servicio1.listarProveedores(texto)
                If ds.Tables(0).Rows.Count > 0 Then
                    lblProveedor.Text = ds.Tables(0).Rows(0)("Descripcion").ToString.Trim
                End If
            End If
        End If
    End Sub

    Sub buscarArticulos()
        If validacion3() = False Then
            dgvArticulos.Rows.Clear()

            Dim famCodigo As String = IIf(cboLineas.SelectedValue.ToString = "0", "", cboLineas.SelectedValue.ToString) &
                                      IIf(cboFamilias.SelectedValue.ToString = "0", "", cboFamilias.SelectedValue.ToString) &
                                      IIf(cboSubFamilias.SelectedValue.ToString = "0", "", cboSubFamilias.SelectedValue.ToString)

            Dim ds As DataSet = servicio2.obtenerArticulosXFiltro(txtArticulo.Text, txtDescripcion.Text, txtProveedor.Text, "00", famCodigo, CInt(txtApartirde.Text), CDec(txtDescuento.Text), "2")

            For i = 0 To ds.Tables(0).Rows.Count - 1
                dgvArticulos.Rows.Add(False, ds.Tables(0).Rows(i)("ART_Codigo").ToString.Trim, ds.Tables(0).Rows(i)("ART_Descripcion").ToString.Trim, ds.Tables(0).Rows(i)("UNM_Abreviatura").ToString.Trim,
                                      ds.Tables(0).Rows(i)("PROV_DesCorta").ToString.Trim, ds.Tables(0).Rows(i)("CantMin1").ToString.Trim, ds.Tables(0).Rows(i)("Dscto1").ToString.Trim,
                                      ds.Tables(0).Rows(i)("CantMin2").ToString.Trim, ds.Tables(0).Rows(i)("Dscto2").ToString.Trim, "+")
            Next
        Else
            If MsgBox("Existen descuentos que no se han guardado, ¿Desea continuar sin guardar?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                limpiar1()
                dgvDescArticulo.Rows.Clear()
                limpiar2()
            End If
        End If
    End Sub

    Private Sub btnBuscar_Click(sender As System.Object, e As System.EventArgs) Handles btnBuscar.Click
        buscarArticulos()
    End Sub

    Private Sub txtApartirde_GotFocus(sender As Object, e As System.EventArgs) Handles txtApartirde.GotFocus
        If txtApartirde.Text = "0" Then
            txtApartirde.Text = ""
        End If
    End Sub

    Private Sub txtApartirde_LostFocus(sender As Object, e As System.EventArgs) Handles txtApartirde.LostFocus
        If txtApartirde.Text = "" Then
            txtApartirde.Text = "0"
        End If
    End Sub

    Private Sub txtDescuento_GotFocus(sender As Object, e As System.EventArgs) Handles txtDescuento.GotFocus
        If txtDescuento.Text = "0.00" Then
            txtDescuento.Text = ""
        End If
    End Sub

    Private Sub txtDescuento_LostFocus(sender As Object, e As System.EventArgs) Handles txtDescuento.LostFocus
        If txtDescuento.Text = "" Then
            txtDescuento.Text = "0.00"
        End If
    End Sub

    Private Sub dgvArticulos_CellContentClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvArticulos.CellContentClick
        Dim f As Integer = e.RowIndex
        Dim c As Integer = e.ColumnIndex

        If f > -1 Then
            If c = 9 Then
                Dim frmDesc As New frmInformacionDescuento(dgvArticulos.Item("Column2", f).Value, dgvArticulos.Item("Column3", f).Value)
                If frmDesc.ShowDialog = Windows.Forms.DialogResult.OK Then

                End If
            End If
        End If
    End Sub

    Sub limpiar2()
        txtApartDe.Text = "1"
        txtDesco.Text = "0.01"
        dtpInicio.Text = Date.Now.ToString("dd/MM/yyyy")
        txtApartDe.Focus()
    End Sub

    Sub agregarDescuentos(aPartirDe As String, desc As String, fecha1 As String, fecha2 As String)
        dgvDescArticulo.Rows.Add(aPartirDe, desc, fecha1, fecha2)

        If dgvDescArticulo.Rows.Count > 0 Then
            dgvDescArticulo.Rows(0).Selected = False
        End If
    End Sub

    Private Sub btnAgregar_Click(sender As System.Object, e As System.EventArgs) Handles btnAgregar.Click
        If validacion1() = True Then
            agregarDescuentos(txtApartDe.Text, txtDesco.Text, dtpInicio.Text, dtpVigencia.Text)
            limpiar2()
        End If
    End Sub

    Sub guardar()
        If dgvArticulos.Rows.Count > 0 Then
            If MsgBox("¿Esta seguro que desea registrar estos descuentos?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                dgvArticulos.EndEdit()

                For Each fila1 As DataGridViewRow In dgvArticulos.Rows
                    If fila1.Cells("Column1").Value = True Then
                        For Each fila2 As DataGridViewRow In dgvDescArticulo.Rows
                            servicio2.registrarDescuentos(CIA, SUC, fila1.Cells("Column2").Value, CInt(fila2.Cells("Column11").Value), CDec(fila2.Cells("Column12").Value), fila2.Cells("Column14").Value, fila2.Cells("Column13").Value)
                        Next
                    End If
                Next
                util.mensaje("Registro completado correctamente.")
                dgvDescArticulo.Rows.Clear()
                limpiar2()
                buscarArticulos()
            End If
        Else
            util.mensaje("No hay descuentos por guardar.")
        End If
    End Sub

    Private Sub btnGuardar_Click(sender As System.Object, e As System.EventArgs) Handles btnGuardar.Click
        guardar()
    End Sub

    Function validacion2() As Boolean
        If txtApd.Text = "" Then
            util.mensaje("Ingrese cantidad mínima.")
            Return False
            Exit Function
        End If
        If CInt(txtApd.Text) < 1 Then
            util.mensaje("No se puede ingresar negativos ni cero.")
            Return False
            Exit Function
        End If
        If Not IsNumeric(txtApd.Text) Then
            util.mensaje("No se puede ingresar letras.")
            Return False
            Exit Function
        End If
        If devuelveMarcadosArticulos(dgvArticulos) < 1 Then
            util.mensaje("Debe seleccionar al menos 1 artículo.")
            Return False
            Exit Function
        End If
        Return True
    End Function

    Sub eliminar()
        If validacion2() = True Then
            If MsgBox("¿Esta seguro que desea eliminar los descuentos?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                dgvArticulos.EndEdit()

                For Each fila As DataGridViewRow In dgvArticulos.Rows
                    If fila.Cells("Column1").Value = True Then
                        servicio2.activarDescuentos(CIA, SUC, fila.Cells("Column2").Value, CInt(txtApd.Text))
                    End If
                Next

                util.mensaje("Se eliminó correctamente.")
                limpiar3()
                buscarArticulos()
            End If
        End If
    End Sub

    Private Sub btnEliminar_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminar.Click
        eliminar()
    End Sub

    Sub limpiar1()
        dgvArticulos.Rows.Clear()
        txtArticulo.Text = ""
        txtDescripcion.Text = ""
        txtProveedor.Text = ""
        lblProveedor.Text = ""
        cboLineas.SelectedIndex = 0
        txtApartirde.Text = "0"
        txtDescuento.Text = "0.00"
        txtArticulo.Focus()
    End Sub

    Private Sub btnLimpiar_Click(sender As System.Object, e As System.EventArgs) Handles btnLimpiar1.Click
        limpiar1()
    End Sub

    Private Sub btnLimpiar2_Click(sender As System.Object, e As System.EventArgs) Handles btnLimpiar2.Click
        dgvDescArticulo.Rows.Clear()
        limpiar2()
    End Sub

    Private Sub dtpInicio_ValueChanged(sender As Object, e As System.EventArgs) Handles dtpInicio.ValueChanged
        If CDate(dtpInicio.Text) < CDate(Date.Now.ToString("dd/MM/yyyy")) Then
            util.mensaje("La fecha no puede ser menor que la actual.")
            dtpInicio.Text = Date.Now.ToString("dd/MM/yyyy")
        Else
            dtpVigencia.Text = dtpInicio.Text
        End If
    End Sub

    Private Sub dtpVigencia_ValueChanged(sender As Object, e As System.EventArgs) Handles dtpVigencia.ValueChanged
        If CDate(dtpVigencia.Text) < CDate(dtpInicio.Text) Then
            util.mensaje("La fecha no puede ser menor que la fecha inicial.")
            dtpVigencia.Text = dtpInicio.Text
        End If
    End Sub

    Function validacion1() As Boolean
        If txtApartDe.Text = "" Then
            util.mensaje("Ingrese la cantidad mínima.")
            Return False
            Exit Function
        End If
        If CInt(txtApartDe.Text) < 1 Then
            util.mensaje("No ingrese cero ni negativos.")
            Return False
            Exit Function
        End If
        If Not IsNumeric(txtApartDe.Text) Then
            util.mensaje("No ingrese letras.")
            Return False
            Exit Function
        End If
        If txtDesco.Text = "" Then
            util.mensaje("Ingrese el descuento.")
            Return False
            Exit Function
        End If
        If CDec(txtDesco.Text) < 0.01 Then
            util.mensaje("No ingrese cero ni negativos.")
            Return False
            Exit Function
        End If
        If Not IsNumeric(txtDesco.Text) Then
            util.mensaje("No ingrese letras.")
            Return False
            Exit Function
        End If
        If devuelveMarcadosArticulos(dgvArticulos) < 1 Then
            util.mensaje("Debe seleccionar al menos 1 artículo.")
            Return False
            Exit Function
        End If
        Return True
    End Function

    Function devuelveMarcadosArticulos(dgv As DataGridView) As Integer
        dgv.EndEdit()
        Dim contador As Integer = 0
        For Each fila As DataGridViewRow In dgv.Rows
            If fila.Cells("Column1").Value = True Then
                contador = contador + 1
            End If
        Next
        Return contador
    End Function

    Sub limpiar3()
        txtApd.Text = "1"
        txtApd.Focus()
    End Sub

    Private Sub btnLim_Click(sender As System.Object, e As System.EventArgs) Handles btnLim.Click
        limpiar3()
    End Sub

    Function validacion3() As Boolean
        If dgvDescArticulo.Rows.Count > 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 1 Then
            If validacion3() = True Then
                If MsgBox("Existen descuentos que no se han guardado, ¿Desea continuar sin guardar?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Mensajes al Usuario") = MsgBoxResult.Yes Then
                    dgvDescArticulo.Rows.Clear()
                    limpiar2()
                End If
            End If
        End If
    End Sub

End Class